package com.tn.openrpc.jms;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.Session;

import org.springframework.jms.support.JmsUtils;

import com.tn.openrpc.util.Factory;
import com.tn.openrpc.util.FactoryException;

/**
 * An implementation of <code>Factory</code> that creates a <i>temporary</i> <code>Queue</code>.  This class is intended
 * to be used with a connection pool so that closing the <code>Connection</code> used to create the <i>temporary</i>
 * <code>Queue</code> simply returns it to the connection pool leaving the <i>temporary</i> <code>Queue</code> in place.
 */
public class TemporaryQueueFactory implements Factory<Queue>
{
  private ConnectionFactory connectionFactory;

  /**
   * Creates a new <code>TemporaryQueueFactory</code>.
   *
   * @param connectionFactory the factory used to obtain a connection.  This should be a connection pool to avoid the
   *                          <i>temporary</i> <code>Queue</code> being closed before it is returned.
   */
  public TemporaryQueueFactory(ConnectionFactory connectionFactory)
  {
    this.connectionFactory = connectionFactory;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Queue newInstance() throws FactoryException
  {
    Connection connection = null;
    Session session = null;

    try
    {
      connection = connectionFactory.createConnection();
      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      return session.createTemporaryQueue();
    }
    catch (JMSException e)
    {
      throw new FactoryException("An error occurred creating a temporary queue.", e);
    }
    finally
    {
      JmsUtils.closeSession(session);
      JmsUtils.closeConnection(connection);
    }
  }
}
